package com.healthcloud.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.healthcloud.dao.GuidIdentCorporeityMapper;
import com.healthcloud.dao.IdentCorporeityResultMapper;
import com.healthcloud.dao.PatientMapper;
import com.healthcloud.dao.PhysicalExamMapper;
import com.healthcloud.entity.GuidIdentCorporeity;
import com.healthcloud.entity.IdentCorporeityResult;
import com.healthcloud.entity.Patient;
import com.healthcloud.entity.PhysicalExam;
import com.healthcloud.service.IdentCorporeityResultService;
import com.healthcloud.utils.DateUtils;
import com.healthcloud.utils.JFreeChart;
import com.healthcloud.vo.IdentCorporeityVo;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.draw.LineSeparator;

/**
 * 体质辨识业务接口实现
 * 
 * @author ZhengL 2015-07-15
 */
@Service
@Transactional
public class IdentCorporeityResultServiceImpl implements
		IdentCorporeityResultService {

	@Autowired
	private IdentCorporeityResultMapper identCorporeityResultMapper;
	@Autowired
	private PatientMapper patientMapper;
	@Autowired
	private PhysicalExamMapper physicalExamMapper;
	@Autowired
	private GuidIdentCorporeityMapper guidIdentCorporeityMapper;
	
	@Override
	public Object parseJsonMap(Map<String, String> jsonMap) {
		return getObject(jsonMap);
	}

	String[] tz = {"平和质","气虚质","阳虚质","阴虚质","痰虚质","湿热质","血瘀质","气郁质","特禀质"};
	
	// 体质辨识类字段匹配
	private IdentCorporeityResult getObject(Map<String, String> jsonMap) {
		IdentCorporeityResult obj = new IdentCorporeityResult();
		if (jsonMap != null && !jsonMap.isEmpty()) {
			String actId = jsonMap.get("id");
			if (!StringUtil.isBlank(actId)) {
				Long id = Long.valueOf(actId);
				if (id > 0) {
					obj = identCorporeityResultMapper.get(id);
				}
			}
//			if (!StringUtil.isBlank(jsonMap.get("examid"))) {
//				obj.setMkExamCode(jsonMap.get("examid"));
//			}
			if (!StringUtil.isBlank(jsonMap.get("mkExamCode"))) {
				obj.setMkExamCode(jsonMap.get("mkExamCode"));
			}
			if (!StringUtil.isBlank(jsonMap.get("answer"))) {
				obj.setAnswer(jsonMap.get("answer"));
			}
			if (!StringUtil.isBlank(jsonMap.get("result"))) {
				obj.setResult(jsonMap.get("result"));
			}
			if (StringUtil.isBlank(actId) || actId == "0" || actId.equals("0")) {
				identCorporeityResultMapper.save(obj);
			} else {
				identCorporeityResultMapper.update(obj);
			}
		}
		return obj;
	}
	
	
	//组装体质信息的结果集
	@Override
	public IdentCorporeityVo findVo(String idCard,String mkCode) throws Exception{
		IdentCorporeityVo vo = new IdentCorporeityVo();
		PhysicalExam entity = new PhysicalExam();
		if(StringUtils.isNotBlank(mkCode)){
			entity.setMkExamCode(mkCode);
		}
		if(StringUtils.isNotBlank(idCard)){
			entity.setIdCard(idCard);
		}
		List<PhysicalExam> list = physicalExamMapper.findByEntity(entity,null);
		PhysicalExam pe = new PhysicalExam();
		if(list!=null&&list.size()>0){ //查找体检信息
			pe = list.get(0);
		}
		Patient pt = patientMapper.findByIdCard(idCard); //查找设置病人信息
		if(pt!=null){ 
			vo.setPatientName(pt.getRealname()); 
			vo.setMedicalCardNum(pt.getMedicalCardNum());
			Date dt = pt.getBirthday();
			Integer ge = pt.getGender();
			if (dt != null) {
				String age = DateUtils.getAge(dt);
				vo.setAge(age);
			}
			if (ge == 0) {
				vo.setSex("女");
			} else {
				vo.setSex("男");
			}
		}
		Date dt2 = pe.getExamDate();
		if (dt2 == null) {
			dt2 = new Date();
		}
		String time = DateUtils.format(DateUtils.Date2Calendar(dt2),"yyyy-MM-dd HH:mm:ss");
		vo.setExamDateStr(time);//设置体检时间
		IdentCorporeityResult entity2 = new IdentCorporeityResult();
		entity2.setMkExamCode(mkCode);
		IdentCorporeityResult ir = findByEntity(entity2); //查找并设置体质信息
		if(ir!=null){
			String[] answer = ir.getAnswer().trim().replace("|", ",").split(",");
			String[] result = ir.getResult().trim().replace("|", ",").split(",");
			vo.setAnswer(answer);
			vo.setResult(result);
			vo.setExamid(ir.getExamId());
		}
		return vo;
	}
	
	//创建柱状图并计算最大得分和兼有体质
	@Override
	public IdentCorporeityVo createChart(String filePath,IdentCorporeityVo vo){
		try{
		DefaultCategoryDataset ds = new DefaultCategoryDataset();
		String[] answer = vo.getAnswer();
		List<String> li = new ArrayList();//兼有体质列表
		double max = 0;//最大得分
		int num = -1; //计数暂存
		String mainBody = "";//主要体质
		if(answer!=null){
			for(int i=0;i<tz.length;i++){
				if(i<answer.length){
					if(StringUtils.isBlank(answer[i])||answer[i]=="0"||answer[i].equals("0")){
						ds.addValue(Double.valueOf(0),"",tz[i]);
					}else{
						Double value = Double.valueOf(answer[i]);
						if(value>max){
							if(num!=-1){
								li.add(tz[i]);
							}
							max = value;
							mainBody = tz[i];
							num = i;
						}else{
							li.add(tz[i]);
						}
						ds.addValue(value,"",tz[i]);//组装柱状图用的数据集
					}
				}
			}
			File file = new File(filePath);
			if(!file.exists()){
				//创建柱状图
				JFreeChart.CreateChart("体质分析图", "体质类别", "得分", ds, filePath);
			}
		}
		vo.setMain(mainBody);//设置主要体质
		vo.setMinor(li);//设置兼有体质
		}catch(Exception e){
			e.printStackTrace();
		}
		return vo;
	}
	
	//查找体质情况
	@Override
	public IdentCorporeityResult findByEntity(IdentCorporeityResult entity){
		IdentCorporeityResult ir = new IdentCorporeityResult();
		List<IdentCorporeityResult> list = identCorporeityResultMapper.findByEntity(entity,null);
		if(list!=null&&list.size()>0){
			ir = list.get(0);
			return ir;
		}else{
			return null;
		}
	}
		
	//查询体质建议
	@Override
	public GuidIdentCorporeity findByEntity(String name){
		GuidIdentCorporeity gc = new GuidIdentCorporeity();
		GuidIdentCorporeity entity = new GuidIdentCorporeity();
		List<GuidIdentCorporeity> list =  guidIdentCorporeityMapper.findByEntity(entity,null);
		if(list!=null&&list.size()>0){
			gc = list.get(0);
			return gc;
		}else{
			return null;
		}
	}
	
	//创建体制报告pdf
	@Override
	public void createPdf(String pdfPath,String imgPath,IdentCorporeityVo vo) throws Exception  {
		Document doc = new Document(PageSize.A4);
		try{
			File file = new File(pdfPath);
			if(!file.exists()){
				GuidIdentCorporeity gc = findByEntity(vo.getMain());
				
				PdfWriter.getInstance(doc, new FileOutputStream(pdfPath));
				doc.open();
				BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				Font FontChinese = new Font(bfChinese, 20, Font.BOLD);
				Font FontChinese2 = new Font(bfChinese, 8, Font.NORMAL);
				Font FontChinese3 = new Font(bfChinese, 14, Font.NORMAL);
				Font FontChinese4 = new Font(bfChinese, 14, Font.BOLD);
				Font FontChinese5 = new Font(bfChinese, 8, Font.BOLD);
				
				PdfPTable table1 = new PdfPTable(4);
				table1.setTotalWidth(150);
				table1.setWidths(new float[] { 50f, 50f, 50f,50f });
				PdfPCell cell1 = new PdfPCell();
				cell1.setColspan(4);
				Paragraph para = new Paragraph("体制分析报告", FontChinese);
				cell1.setPhrase(para);
				cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
				cell1.setBorderColor(BaseColor.WHITE);
				cell1.setMinimumHeight(40f);
				table1.addCell(cell1);
				PdfPCell cell2 = new PdfPCell();
				cell2.setPhrase(new Paragraph("姓名：" + vo.getPatientName(),FontChinese2));
				cell2.setBorderColor(BaseColor.WHITE);
				cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
				table1.addCell(cell2);
				PdfPCell cell3 = new PdfPCell();
				cell3.setPhrase(new Paragraph("性别："+vo.getSex(), FontChinese2));
				cell3.setBorderColor(BaseColor.WHITE);
				cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
				table1.addCell(cell3);
				PdfPCell cell4 = new PdfPCell();
				cell4.setPhrase(new Paragraph("年龄："+vo.getAge(), FontChinese2));
				cell4.setBorderColor(BaseColor.WHITE);
				cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
				table1.addCell(cell4);
				PdfPCell cell5 = new PdfPCell();
				cell5.setPhrase(new Paragraph("体检时间：" + vo.getExamDateStr(), FontChinese2));
				cell5.setBorderColor(BaseColor.WHITE);
				cell5.setNoWrap(true);
				cell5.setHorizontalAlignment(Element.ALIGN_CENTER);
				table1.addCell(cell5);
				doc.add(table1);
				Paragraph p1 = new Paragraph(new Chunk(new LineSeparator(1, 100,null, Element.ALIGN_BOTTOM, 10)));
				doc.add(p1);
				
				Image img = Image.getInstance(imgPath);  //体质分析柱状图
				img.setAlignment(Image.RIGHT | Image.TEXTWRAP);  
				img.setBorder(Image.BOX);  
				img.setBorderWidth(1);  
				img.setBorderColor(BaseColor.WHITE);  
				img.scaleToFit(350, 250);//大小  
				
				PdfPTable table = new PdfPTable(2);
				table.setWidthPercentage(100);
				table.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.setWidths(new float[] { 25f, 75f,});
				PdfPCell cell = new PdfPCell();
				
				Paragraph  paragraph1 = new Paragraph();
				Phrase phrase1 = new Phrase("我的主要体质:\n\n",FontChinese3);
				Phrase phrase2 = new Phrase(" "+vo.getMain()+"\n\n",FontChinese4);
				Phrase phrase3 = new Phrase("兼有体质:\n\n",FontChinese3);
				paragraph1.add(phrase1);
				paragraph1.add(phrase2);
				paragraph1.add(phrase3);
				for(int i=0;i<vo.getMinor().size(); i++){
					String minor = vo.getMinor().get(i);
					Phrase phraseTemp = null;
					if(i%2==1){
						phraseTemp = new Phrase(" "+minor+"\n\n",FontChinese2);
					}else{
						 phraseTemp = new Phrase(" "+minor+" ",FontChinese2);
					}
					paragraph1.add(phraseTemp);
				}
				cell.setPhrase(paragraph1);
				cell.setHorizontalAlignment(Element.ALIGN_LEFT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				cell = new PdfPCell(img);//插入柱状图
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				doc.add(table);
				Paragraph p = new Paragraph(new Chunk(new LineSeparator(0, 100,BaseColor.LIGHT_GRAY, Element.ALIGN_BOTTOM, 5)));
				doc.add(p);
				
				table = new PdfPTable(1);
				table.setWidthPercentage(100);
				table.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.setWidths(new float[] {100f});
				cell = new PdfPCell();
				cell.addElement(new Paragraph(vo.getMain()+"体质特征:", FontChinese5));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				cell = new PdfPCell();
				cell.addElement(new Paragraph(gc.getFeature(), FontChinese2));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				doc.add(table);
				
				doc.add(p);
				
				table = new PdfPTable(1);
				table.setWidthPercentage(100);
				table.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.setWidths(new float[] {100f});
				cell = new PdfPCell();
				cell.addElement(new Paragraph(vo.getMain()+"发病倾向:", FontChinese5));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				cell = new PdfPCell();
				cell.addElement(new Paragraph(gc.getIncidenceTendency(), FontChinese2));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				doc.add(table);
				
				doc.add(p);
				
				table = new PdfPTable(1);
				table.setWidthPercentage(100);
				table.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.setWidths(new float[] {100f});
				cell = new PdfPCell();
				cell.addElement(new Paragraph(vo.getMain()+"饮食建议:", FontChinese5));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				cell = new PdfPCell();
				cell.addElement(new Paragraph(gc.getDietGuid(), FontChinese2));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				doc.add(table);
				
				doc.add(p);
				
				table = new PdfPTable(1);
				table.setWidthPercentage(100);
				table.setHorizontalAlignment(Element.ALIGN_CENTER);
				table.setWidths(new float[] {100f});
				cell = new PdfPCell();
				cell.addElement(new Paragraph(vo.getMain()+"保健建议:", FontChinese5));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				cell = new PdfPCell();
				cell.addElement(new Paragraph(gc.getHealthcareGuid(), FontChinese2));
				cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
				cell.setBorderColor(BaseColor.WHITE);
				table.addCell(cell);
				doc.add(table);
				doc.close();
			}
		}catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	//体质报告添加背景图
	@Override
     public void createBackground(String source,String target,String imagPath){
    	 try{
    		File file = new File(target);
 			if(!file.exists()){
 				PdfReader reader = new PdfReader(source);  
 	 			PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(target)); 
 	 			Image img1 = Image.getInstance(imagPath);
 	 			img1.setAbsolutePosition(0, 0);  
 	 			PdfContentByte under1 = stamp.getUnderContent(1);  
 	 			under1.addImage(img1);  
 	 			stamp.close();
 	 			reader.close();
 	 			File file2 = new File(source);
 	 			if (file2.isFile() && file2.exists()) {  
 	 				file2.delete();  
 	 		    }  
 			}
    	 }catch (MalformedURLException e) {
 			e.printStackTrace();
 		 }catch (FileNotFoundException e) {
 			e.printStackTrace();
 		 } catch (DocumentException e) {
 			e.printStackTrace();
 		 }catch (IOException e) {
			e.printStackTrace();
		 }  
     } 
	
	
}
